# -*- coding: utf-8 -*-
# בש״ד
#
# Miramar CMS for Django - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
# 
# Por mi amor, que inspira a mi cada respiración y que echa de Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django import forms
from django.utils.translation import ugettext as _
from miramar import models as miramar
from miramar import api
from miramar import settings

class PageForm(forms.ModelForm):
    def __init__(self, slug, user, *args, **kwargs):
        super(PageForm, self).__init__(*args, **kwargs)
        self.slug = slug
        self.user = user
    
    def save(self, commit=True):
        new_obj = super(PageForm, self).save(commit=False)
        new_obj.slug = self.slug.lower()
        if not new_obj.id:
            new_obj.created_by = self.user
        if commit:
            new_obj.save(user=self.user)
        return new_obj
        
    markup_engine = forms.ChoiceField(
        label=_(u'Markup engine'),
        choices=api.IMiramarMarkupEngine.get_registered_components())
    
    class Meta:
        model = miramar.Page
        exclude = ['slug', 'created_by']
    
    class Media:
            js = (settings.JQUERY_URLSTUB, settings.SIMPLEMODAL_JS_URLSTUB)

class PageSlugChangeForm(forms.Form):
    new_slug = forms.SlugField(required=True,
                               label=_(u'New URL stub'),
                               max_length=120)
    create_redirect = forms.BooleanField(
        label=_(u'Create redirect?'),
        help_text=_((u'Any requests for the current stub will redirect to '
                     u'the new stub. If you later create a new page with the '
                     u'same stub, the redirect will stop.')),
        required=False,
        initial=True)
    
    def __init__(self, rename_from, *args, **kwargs):
        super(PageSlugChangeForm, self).__init__(*args, **kwargs)
        self.old_slug = rename_from
    
    def clean_new_slug(self):
        new_slug = self.cleaned_data['new_slug']
        
        if new_slug.lower() == self.old_slug.lower():
            raise forms.ValidationError(
                _((u'The new stub you provided is the same as the old stub. '
                   u'URL stubs are case insensitive.')))
        if miramar.Page.on_site.filter(slug__iexact=new_slug).count():
            raise forms.ValidationError(
                _(u'There already exists a page with that URL stub.'))
        return new_slug

class PageVersionTagForm(forms.Form):
    def __init__(self, page_obj, *args, **kwargs):
        self.page_obj = page_obj
        super(PageVersionTagForm, self).__init__(*args, **kwargs)
    
    version_tag = forms.CharField(label=_(u'Version tag'),
                                  max_length=50)
    
    def clean_version_tag(self):
        # Make sure this version tag does not already exist for this page
        try:
            self.page_obj.pageversion_set.filter(
                version_tag=self.cleaned_data['version_tag'])[0]
        except IndexError:
            # Good! It does not exist
            return self.cleaned_data['version_tag']
        else:
            # Uh-oh. Already exists.
            raise forms.ValidationError(
                _(u'There is already a version tag %s for this page.') % \
                self.cleaned_data['version_tag'])

class PageVersionUpdateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PageVersionUpdateForm, self).__init__(*args, **kwargs)
        try:
            from markitup.forms import MarkItUpWidget
        except ImportError:
            pass
        else:
            instance = kwargs['instance']
            self.fields['body'].widget = MarkItUpWidget(
                markup_set=instance.page.markup_engine.get_markup_type())
    
    class Meta:
        model = miramar.PageVersion
        fields = ['body', 'comment']


class StoredImageUpdateForm(forms.ModelForm):
    class Meta:
        model = miramar.StoredImage
        exclude = ['slug']

class StoredFileUpdateForm(forms.ModelForm):
    class Meta:
        model = miramar.StoredFile
        exclude = ['slug']
